package com.mindmax.wordmemory.controller;

import com.alibaba.fastjson2.JSON;
import com.aliyun.oss.ServiceException;
import com.mindmax.wordmemory.domain.VocabularyBank;
import com.mindmax.wordmemory.mapper.DataVocabularyItemMapper;
import com.mindmax.wordmemory.mapper.DataVocabularySourceMapper;
import com.mindmax.wordmemory.service.IVocabularyBankService;
import com.mindmax.wordmemory.vo.VocabularySource;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.mq.ZeroMqSender;
import com.ruoyi.common.oss.AliyunOss;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 单词库Controller
 * 
 * @author ruoyi
 * @date 2024-04-03
 */

@RestController
@RequestMapping("/word-memory/vocabulary-bank")
@DataSource(value = DataSourceType.WORD_MEMORY)
@Slf4j
public class VocabularyBankController extends BaseController
{


    @Autowired
    private IVocabularyBankService vocabularyBankService;

    @Autowired
    private AliyunOss aliyunOss;

    @Autowired
    private ZeroMqSender zeroMqSender;
    @Anonymous
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, @RequestParam(value = "bankId") Long bankId) {
        log.info("#####################  bankId = {}", bankId);
        try
        {
            String url = aliyunOss.upload(file);
            log.info("#####################  upload url = " + url);
            ExcelUtil<VocabularySource> util = new ExcelUtil<>(VocabularySource.class);

            List<VocabularySource> vocabularySources = util.importExcel(file.getInputStream());

            log.info("#####################  upload vocabularySources = " + JSON.toJSONString(vocabularySources));

            if (CollectionUtils.isEmpty(vocabularySources)) {
                throw new ServiceException("上传文件无效");
            }

            Long userId = getUserId();
            vocabularySources
                    = vocabularySources.stream().peek(x ->
                    {
                        x.setUid(userId);x.setBankId(bankId);
                    }
            ).collect(Collectors.toList());
            dataVocabularyItemMapper.deleteDataVocabularyItemByBankId(bankId);
            log.info("#########  相关词库已清空 #########");
            zeroMqSender.sendMessage(JSON.toJSONString(vocabularySources));
            log.info("#########  已发送至消息队列 #########");
            //清理旧库
            AjaxResult ajax = AjaxResult.success();
            String fileName = FileUtils.getName(url);
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }



    @Resource
    private DataVocabularyItemMapper   dataVocabularyItemMapper;


    /**
     * 查询单词库列表
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:list')")
    @GetMapping("/list")
    public TableDataInfo list(VocabularyBank vocabularyBank)
    {
        startPage();
        List<VocabularyBank> list = vocabularyBankService.selectVocabularyBankList(vocabularyBank);
        return getDataTable(list);
    }

    /**
     * 导出单词库列表
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:export')")
    @Log(title = "单词库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VocabularyBank vocabularyBank)
    {
        List<VocabularyBank> list = vocabularyBankService.selectVocabularyBankList(vocabularyBank);
        ExcelUtil<VocabularyBank> util = new ExcelUtil<VocabularyBank>(VocabularyBank.class);
        util.exportExcel(response, list, "单词库数据");
    }

    /**
     * 获取单词库详细信息
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(vocabularyBankService.selectVocabularyBankById(id));
    }

    /**
     * 新增单词库
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:add')")
    @Log(title = "单词库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VocabularyBank vocabularyBank)
    {
        return toAjax(vocabularyBankService.insertVocabularyBank(vocabularyBank));
    }

    /**
     * 修改单词库
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:edit')")
    @Log(title = "单词库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VocabularyBank vocabularyBank)
    {
        return toAjax(vocabularyBankService.updateVocabularyBank(vocabularyBank));
    }

    /**
     * 删除单词库
     */
    @PreAuthorize("@ss.hasPermi('word_memory:vocabulary_bank:remove')")
    @Log(title = "单词库", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(vocabularyBankService.deleteVocabularyBankByIds(ids));
    }
}
